<template>
    <el-form :model="courseInfo" label-position="top" v-loading="loading" ref="formRefs" :rules="rules">
        <el-form-item size="large" :label="$t('course.edit.label_1')" prop="image_url">
            <el-upload :show-file-list="false" :before-upload="beforeUpload" accept="image/jpeg, image/png" :http-request="handleUpload">
                <div class="unit-img pic">
                    <img v-if="courseInfo.image_url" :src="courseInfo.image_url" class="ele" />
                    <el-icon v-else size="35" color="#dcdfe6"><Plus /></el-icon>
                </div>
                <template #tip>
                    <p>{{ $t('course.edit.label_1_placeholder') }}</p>
                </template>
            </el-upload>
        </el-form-item>
        <el-row :gutter="30">
            <el-col :span="12">
                <el-form-item size="large" :label="$t('course.edit.label_2')" prop="name">
                    <el-input v-model="courseInfo.name" :placeholder="$t('course.edit.label_2_placeholder')" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item size="large" :label="$t('course.edit.label_3')" prop="short_name">
                    <el-input v-model="courseInfo.short_name" :placeholder="$t('course.edit.label_3_placeholder')" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-form-item size="large" :label="$t('course.edit.label_4')" prop="description">
            <RichTextEditor v-model="courseInfo.description" @update-richValue="courseInfo.description = $event" />
        </el-form-item>
        <el-row :gutter="30">
            <el-col :span="12">
                <el-form-item size="large" :label="$t('course.edit.label_5')" prop="course_id">
                    <el-input type="number" v-model="courseInfo.course_id" :placeholder="$t('course.edit.label_5_placeholder')" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item size="large" :label="$t('course.edit.label_6')" prop="category_id">
                    <el-tree-select v-model="courseInfo.category_id" :data="categoryList" :props="defaultProps" :placeholder="$t('course.edit.label_6_placeholder')" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="30">
            <el-col :span="12">
                <el-form-item size="large" :label="$t('course.edit.label_7')" prop="dateRange">
                    <el-date-picker
                        v-model="dateRange"
                        type="datetimerange"
                        range-separator="-"
                        :start-placeholder="$t('course.edit.label_7_placeholder_1')"
                        :end-placeholder="$t('course.edit.label_7_placeholder_2')"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item size="large" :label="$t('course.edit.label_8')" prop="report_deadline">
                    <el-date-picker v-model="courseInfo.report_deadline" type="datetime" :placeholder="$t('course.edit.label_8_placeholder')" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="30">
            <el-col :span="8" v-if="courseId">
                <el-form-item size="large" :label="$t('course.edit.label_9')" prop="is_active">
                    <el-switch v-model="courseInfo.is_active" :active-value="2" :inactive-value="1" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-form-item>
            <div class="btn-list">
                <el-button color="#f06423" @click="handleSave(false)">{{ $t('golbal.btn_text_1') }}</el-button>
                <el-button color="#f06423" @click="handleSave(true)">{{ $t('golbal.btn_text_2') }}</el-button>
                <el-button color="#f06423" @click="router.go(-1)">{{ $t('golbal.btn_text_3') }}</el-button>
            </div>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type UploadRequestOptions } from 'element-plus'
import moment from 'moment'

import RichTextEditor from '@/components/RichTextEditor.vue'

import { useRoleStore } from '@/stores/role'

import CourseService from '@/api/course'
import type { CourseCreateItem, CourseItem } from '@/types/course'

import CourseCategoryService from '@/api/courseCategory'
import type { CourseCategoryItem } from '@/types/courseCategory'

import ResourceService from '@/api/resource'

import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

const route = useRoute()
const router = useRouter()
const courseId = computed(() => Number(route.params.courseId))
const categoryId = computed(() => Number(route.query.categoryId))
const cloneId = computed(() => Number(route.query.cloneId))
const loading = ref(false)
const { t } = useI18n<{ message: MessageSchema }, SupportedLocales>()

const courseInfo = ref<CourseCreateItem>({
    image_url: '',
    name: '',
    short_name: '',
    description: '',
    course_id: '',
    category_id: categoryId.value || null,
    report_deadline: null,
    is_active: 1,
    start_date: '',
    end_date: '',
})
const dateRange = computed({
    get: () => [courseInfo.value.start_date, courseInfo.value.end_date],
    set: (val: [string, string]) => {
        courseInfo.value.start_date = moment(val[0]).format('YYYY-MM-DD HH:mm:ss')
        courseInfo.value.end_date = moment(val[1]).format('YYYY-MM-DD HH:mm:ss')
    },
})
function getCourseInfo() {
    loading.value = true
    const _id = courseId.value || cloneId.value
    CourseService.getById(_id)
        .then(res => {
            if (courseId.value) {
                const { id, image_url, name, short_name, description, course_id, category_id, report_deadline, is_active, start_date, end_date } = res
                courseInfo.value = { id, image_url, name, short_name, description, course_id, category_id, report_deadline, is_active, start_date, end_date }
            }
            if (cloneId.value) {
                const { id, ...rest } = res
                courseInfo.value = rest
            }
        })
        .finally(() => {
            loading.value = false
        })
}

// 表单行为
const formRefs = ref<FormInstance>()
const rules = {
    name: [{ required: true, message: t('course.edit.label_2_msg'), trigger: 'blur' }],
    short_name: [{ required: true, message: t('course.edit.label_3_msg'), trigger: 'blur' }],
    course_id: [{ required: true, message: t('course.edit.label_5_msg'), trigger: 'blur' }],
    category_id: [{ required: true, message: t('course.edit.label_6_msg'), trigger: 'blur' }],
    dateRange: [
        {
            required: true,
            validator: (rule: any, value: [string, string], callback: any) => {
                if (!courseInfo.value.start_date && courseInfo.value.end_date) {
                    callback(new Error(t('course.edit.label_7_msg')))
                } else {
                    callback()
                }
            },
            trigger: 'change', // 建议改为change事件触发
        },
    ],
    report_deadline: [{ required: true, message: t('course.edit.label_8_msg'), trigger: 'blur' }],
    is_user: [{ required: true, message: t('course.edit.label_9_msg'), trigger: 'blur' }],
}
const handleSave = (isSaveAndReturn: boolean) => {
    formRefs.value?.validate(valid => {
        if (valid) {
            loading.value = true
            if (courseId.value) {
                CourseService.update(courseInfo.value)
                    .then(() => {
                        if (isSaveAndReturn) router.go(-1)
                    })
                    .finally(() => {
                        loading.value = false
                    })
            } else {
                CourseService.create(courseInfo.value)
                    .then(res => {
                        if (isSaveAndReturn) {
                            router.go(-1)
                        } else {
                            courseInfo.value.id = res.id
                            router.replace({
                                name: 'courseEdit',
                                params: { courseId: res.id },
                            })
                        }
                    })
                    .finally(() => {
                        loading.value = false
                    })
            }
        }
    })
}

// 课程分类列表
const categoryList = ref<CourseCategoryItem[]>([])
const defaultProps = {
    children: 'children',
    label: 'name',
    value: 'id',
}
function getCategoryList() {
    CourseCategoryService.list().then(res => {
        categoryList.value = res.items
        courseInfo.value.category_id = categoryId.value || courseInfo.value.category_id
    })
}

// 角色列表
const roleStore = useRoleStore()
const roleList = computed(() => roleStore.roles)

// 上传
const beforeUpload = (file: File) => {
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error(`${t('golbal.upload_err_1')} 2MB!`)
        return false
    }
    return true
}
const handleUpload = (options: UploadRequestOptions) => {
    const { file } = options
    const data = new FormData()
    data.append('file', file)
    data.append('type', 'image')
    data.append('filename', file.name)
    ResourceService.upload(data).then(res => {
        if (courseInfo.value) courseInfo.value.image_url = res.url
    })
}

onMounted(() => {
    getCategoryList()
    if (courseId.value || cloneId.value) getCourseInfo()
})
</script>

<style lang="less" scoped>
.el-form {
    .el-form-item {
        p {
            margin-top: 4px;
            font-size: 12px;
            color: #4c4c4c;
            line-height: 1.2;
        }

        :deep(.el-input) {
            width: 100%;
        }

        .btn-list {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
        }
    }
}

:deep(.el-upload) {
    .unit-img {
        border: 1px solid #dcdfe6;
        width: 100px;
        height: 100px;

        display: flex;
        align-items: center;
        justify-content: center;
    }
}

:deep(.ck-editor) {
    width: 100%;

    .ck-editor__main {
        .ck-content {
            min-height: 350px;
            max-height: 600px;
        }
    }
}
</style>
